//
//  SampleViewController.m
//  CairnStory
//  www.cairnstory.com
//
//  Created by saturna on 11. 3. 22..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SampleViewController.h"
#import "Me2DaySessionController.h"
#import "Me2DayOAuthResult.h"
#import "Me2DayRequest.h"
#import "Me2DayAttach.h"
#import "Me2DayUIAlertView.h"
#import "Me2DayUtil.h"



#pragma mark -
#pragma mark SampleViewController (PrivateMethods)

@interface SampleViewController (PrivateMethods)

- (void)updateUI;
- (void)startProgressIndicator;
- (void)stopProgressIndicator;

#pragma mark -
- (void)loginMe2Day;
- (void)logoutMe2Day;
- (void)forceLogoutMe2Day;
- (void)me2dayLogoutAfterConfirmView:(Me2DayUIAlertView*)alertView buttonAtIndex:(NSUInteger)buttonIndex;

#pragma mark -
- (void)postMessageWithConfirm:(BOOL)confirm;
- (void)postMessageAfterConfirmView:(Me2DayUIAlertView*)alertView buttonAtIndex:(NSUInteger)buttonIndex;
- (void)postMessage;
- (void)openMessageURLWithConfirmMessage:(NSString*)confirmMessage;
- (void)openMessageURLAfterConfirmView:(Me2DayUIAlertView*)alertView
						 buttonAtIndex:(NSUInteger)buttonIndex;

#pragma mark -
- (void)postPhotoWithConfirm:(BOOL)confirm;
- (void)postPhotoAfterConfirmView:(Me2DayUIAlertView*)alertView buttonAtIndex:(NSUInteger)buttonIndex;
- (void)postPhoto;
- (void)openPhotoURLWithConfirmMessage:(NSString*)confirmMessage;
- (void)openPhotoURLAfterConfirmView:(Me2DayUIAlertView*)alertView
					   buttonAtIndex:(NSUInteger)buttonIndex;

@end


#pragma mark -

#define kMe2DayTagLogin 1
#define kMe2DayTagPostMessage 2
#define kMe2DayTagPostPhoto 3



#pragma mark -
#pragma mark SampleViewController

@implementation SampleViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
	m_progressIndicatorView.hidden = YES;

	[self updateUI];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
	[super viewDidUnload];
}


- (void)dealloc
{
	[m_statusLabel release];
	[m_progressIndicatorView release];

	[m_loginButton release];
	[m_postMessageButton release];
	[m_postPhotoButton release];

	if (m_me2daySessionController != nil)
	{
		[m_me2daySessionController release];
		m_me2daySessionController = nil;
	}

	if (m_me2dayRequest != nil)
	{
		[m_me2dayRequest release];
		m_me2dayRequest = nil;
	}

    [super dealloc];
}



#pragma mark -
#pragma mark button actions

- (IBAction)tapLoginButton:(id)sender
{
	//if (DEBUG) Me2Log(@"====> aaa");
	if ([self.appDelegate isMe2DayAuthorized])
	{
		//if (DEBUG) Me2Log(@"====> bbb");
		[self logoutMe2Day];
	}
	else
	{
		//if (DEBUG) Me2Log(@"====> ccc");
		[self loginMe2Day];
	}
}

- (IBAction)tapPostMessageButton:(id)sender
{
	[self postMessageWithConfirm:YES];
}


- (IBAction)tapPostPhotoButton:(id)sender
{
	[self postPhotoWithConfirm:YES];
}





#pragma mark -
#pragma mark Me2DaySessionDelegate

- (void)me2daySessionController:(Me2DaySessionController*)controller
				didStartWithTag:(NSUInteger)me2dayTag
{
	// do nothing
}

- (void)me2daySessionController:(Me2DaySessionController*)controller
				didLoginWithTag:(NSUInteger)me2dayTag
				 withAuthResult:(Me2DayOAuthResult*)authResult
{
	[self updateUI];
	if (kMe2DayTagLogin == me2dayTag)
	{

	}
	else if (kMe2DayTagPostMessage == me2dayTag)
	{
		[self postMessageWithConfirm:YES];
	}
	else if (kMe2DayTagPostPhoto == me2dayTag)
	{
		[self postPhotoWithConfirm:YES];
	}
}

- (void)me2daySessionController:(Me2DaySessionController*)controller
			   didRejectWithTag:(NSUInteger)me2dayTag
				 withAuthResult:(Me2DayOAuthResult*)authResult
					withMessage:(NSString*)alertMessage
{
	[self showAlertView:alertMessage];
}

- (void)me2daySessionController:(Me2DaySessionController*)controller
			   didCancelWithTag:(NSUInteger)me2dayTag
{
	// do nothing
}

- (void)me2daySessionController:(Me2DaySessionController*)controller
				 didFailWithTag:(NSUInteger)me2dayTag
					withMessage:(NSString*)alertMessage
					  withError:(NSError*)error
{
	if (error == nil)
	{
		[self showAlertView:alertMessage];
	}
	else
	{
		[self showAlertView:[alertMessage stringByAppendingFormat:@"\n%@", [error localizedDescription]]];
	}
}

- (void)me2daySessionController:(Me2DaySessionController*)controller
			   didFinishWithTag:(NSUInteger)me2dayTag
{
	if (m_me2daySessionController != nil)
	{
		[m_me2daySessionController release];
		m_me2daySessionController = nil;
	}
}


#pragma mark -
#pragma mark Me2DayRequestDelegate

- (void)me2dayRequest:(Me2DayRequest*)request
	  didStartWithTag:(NSUInteger)me2dayTag
{
	[self startProgressIndicator];
}


- (void)me2dayRequest:(Me2DayRequest*)request
	didSuccessWithTag:(NSUInteger)me2dayTag
		   withResult:(id)result
{
	if (kMe2DayTagPostMessage == me2dayTag)
	{
		[self openMessageURLWithConfirmMessage:@"message post secceeded!!\nme2day에서 확인하시겠습니까?"];
	}
	else if (kMe2DayTagPostPhoto == me2dayTag)
	{
		[self openPhotoURLWithConfirmMessage:@"photo post secceeded!!\nme2day에서 확인하시겠습니까?"];
	}
}


- (void)me2dayRequest:(Me2DayRequest*)request
	   didFailWithTag:(NSUInteger)me2dayTag
		  withMessage:(NSString*)alertMessage
			withError:(NSError*)error
{
	[self stopProgressIndicator];
	[self showAlertView:alertMessage];
}


- (void)me2dayRequest:(Me2DayRequest*)request
	 didFinishWithTag:(NSUInteger)me2dayTag
{
	[self stopProgressIndicator];
	if (m_me2dayRequest != nil)
	{
		[m_me2dayRequest release];
		m_me2dayRequest = nil;
	}
}






#pragma mark -
#pragma mark SampleViewController (PrivateMethods)

- (void)updateUI
{
	if ([self.appDelegate isMe2DayAuthorized])
	{
		m_statusLabel.text = [NSString stringWithFormat:@"user : %@",
							  self.appDelegate.me2dayOAuthResult.userId];
		[m_loginButton setTitle:@"me2day logout" forState:UIControlStateNormal];
	}
	else
	{
		m_statusLabel.text = @"not login";
		[m_loginButton setTitle:@"me2day login" forState:UIControlStateNormal];
	}
}


- (void)startProgressIndicator
{
	if ([m_progressIndicatorView isAnimating])
	{
		return;
	}
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

	m_progressIndicatorView.hidden = NO;
	[m_progressIndicatorView startAnimating];

	self.view.userInteractionEnabled = NO;
	self.navigationBarUserInteractionEnabled = NO;
}

- (void)stopProgressIndicator
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

	m_progressIndicatorView.hidden = YES;
	[m_progressIndicatorView stopAnimating];

	self.view.userInteractionEnabled = YES;
	self.navigationBarUserInteractionEnabled = YES;
}



#pragma mark -

- (void)loginMe2Day
{
	if (m_me2daySessionController != nil)
	{
		[m_me2daySessionController release];
		m_me2daySessionController = nil;
	}

	m_me2daySessionController = [[Me2DaySessionController alloc] init];
	m_me2daySessionController.delegate = self;
	m_me2daySessionController.me2dayTag = kMe2DayTagLogin;
	[m_me2daySessionController login];
}

- (void)logoutMe2Day
{
	Me2DayUIAlertView* alertView = [[[Me2DayUIAlertView alloc]
								initConfirmWithTitle:nil
								message:@"logout from the me2day?"
								target:self
								action:@selector(me2dayLogoutAfterConfirmView:buttonAtIndex:)] autorelease];
	[alertView show];
}

- (void)forceLogoutMe2Day
{
	self.appDelegate.me2dayOAuthResult = nil;
	[self updateUI];
}

- (void)me2dayLogoutAfterConfirmView:(Me2DayUIAlertView*)alertView buttonAtIndex:(NSUInteger)buttonIndex
{
	if (buttonIndex == 1)
	{
		[self forceLogoutMe2Day];
	}
}





#pragma mark -
- (void)postMessageWithConfirm:(BOOL)confirm
{
	if ([self.appDelegate isMe2DayAuthorized] == NO)
	{
		if (m_me2daySessionController != nil)
		{
			[m_me2daySessionController release];
			m_me2daySessionController = nil;
		}
		m_me2daySessionController = [[Me2DaySessionController alloc] init];
		m_me2daySessionController.delegate = self;
		m_me2daySessionController.me2dayTag = kMe2DayTagPostMessage;
		[m_me2daySessionController login];
		return;
	}

	if (confirm)
	{
		Me2DayUIAlertView* alertView = [[[Me2DayUIAlertView alloc]
										 initConfirmWithTitle:nil
										 message:@"post message?"
										 target:self
										 action:@selector(postMessageAfterConfirmView:buttonAtIndex:)] autorelease];
		[alertView show];
	}
	else
	{
		[self postMessage];
	}
}

- (void)postMessageAfterConfirmView:(Me2DayUIAlertView*)alertView buttonAtIndex:(NSUInteger)buttonIndex
{
	if (buttonIndex == 0)
	{
		return;
	}

	[self postMessage];
}

- (void)postMessage
{

	if (m_me2dayRequest != nil)
	{
		[m_me2dayRequest release];
		m_me2dayRequest = nil;
	}

	//if (DEBUG) Me2Log(@"====> ready postMessage");

	// 주의 : 게시된 내용과 같은 내용을 연속으로 게시되는 경우 미투데이에서 오류발생...
	NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
	NSString* postTags = @"cairnstory";
	NSString* postMessage = [NSString stringWithFormat:
							 @"Hello me2day!! -%@- \r\n\r\n\"www.CairnStory.com\":http://www.cairnstory.com",
							 [Me2DayUtil formatDate:[NSDate date] style:@"yyyy.MM.dd (E) HH:mm:ss"]];

	[params setObject:postMessage forKey:@"post[body]"];
	[params setObject:postTags forKey:@"post[tags]"];
	[params setObject:@"1" forKey:@"post[icon]"];
	//[params setObject:@"true" forKey:@"receive_sms"];
	//[params setObject:@"false" forKey:@"close_comment"];

	NSString* locationTitle = @"location title";
	CGFloat locationLatitude = 37.255109;
	CGFloat locationLongitude = 127.070973;

	[params setObject:locationTitle forKey:@"location"];
	[params setObject:[NSString stringWithFormat:@"%f", locationLatitude] forKey:@"latitude"];
	[params setObject:[NSString stringWithFormat:@"%f", locationLongitude] forKey:@"longitude"];

	m_me2dayRequest = [[Me2DayRequest alloc] initWithMe2DayOAuthResult:self.appDelegate.me2dayOAuthResult];
	m_me2dayRequest.delegate = self;
	m_me2dayRequest.me2dayTag = kMe2DayTagPostMessage;

	[m_me2dayRequest requestWithMethodName:Me2DayRequestMethodCreatePost
								 andParams:[params autorelease]
							 andHttpMethod:@"POST"
							  andMultipart:NO];
}

- (void)openMessageURLWithConfirmMessage:(NSString*)confirmMessage
{
	Me2DayUIAlertView* alertView = [[[Me2DayUIAlertView alloc]
									 initConfirmWithTitle:nil
									 message:confirmMessage
									 target:self
									 action:@selector(openMessageURLAfterConfirmView:buttonAtIndex:)] autorelease];

	[alertView show];
}

- (void)openMessageURLAfterConfirmView:(Me2DayUIAlertView*)alertView
						 buttonAtIndex:(NSUInteger)buttonIndex
{
	if (buttonIndex == 0)
	{
		return;
	}

	NSString* urlString = [NSString stringWithFormat:@"http://me2day.net/%@",
						   self.appDelegate.me2dayOAuthResult.userId ];
	NSURL* aURL = [[NSURL alloc] initWithString:urlString];
	[[UIApplication sharedApplication] openURL:[aURL autorelease]];
}



#pragma mark -

- (void)postPhotoWithConfirm:(BOOL)confirm
{
	if ([self.appDelegate isMe2DayAuthorized] == NO)
	{
		if (m_me2daySessionController != nil)
		{
			[m_me2daySessionController release];
			m_me2daySessionController = nil;
		}
		m_me2daySessionController = [[Me2DaySessionController alloc] init];
		m_me2daySessionController.delegate = self;
		m_me2daySessionController.me2dayTag = kMe2DayTagPostPhoto;
		[m_me2daySessionController login];
		return;
	}

	if (confirm)
	{
		Me2DayUIAlertView* alertView = [[[Me2DayUIAlertView alloc]
										 initConfirmWithTitle:nil
										 message:@"post photo?"
										 target:self
										 action:@selector(postPhotoAfterConfirmView:buttonAtIndex:)] autorelease];
		[alertView show];
	}
	else
	{
		[self postPhoto];
	}
}

- (void)postPhotoAfterConfirmView:(Me2DayUIAlertView*)alertView buttonAtIndex:(NSUInteger)buttonIndex
{
	if (buttonIndex == 0)
	{
		return;
	}

	[self postPhoto];
}

- (void)postPhoto
{
	if (m_me2dayRequest != nil)
	{
		[m_me2dayRequest release];
		m_me2dayRequest = nil;
	}

	//if (DEBUG) Me2Log(@"====> ready postPhoto");

	// 주의 : 게시된 내용과 같은 내용을 연속으로 게시되는 경우 미투데이에서 오류발생...
	NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
	NSString* postTags = @"cairnstory";
	NSString* postMessage = [NSString stringWithFormat:
							 @"Hello me2day!! -%@- \r\n\r\n\"www.CairnStory.com\":http://www.cairnstory.com",
							 [Me2DayUtil formatDate:[NSDate date] style:@"yyyy.MM.dd (E) HH:mm:ss"]];

	[params setObject:postMessage forKey:@"post[body]"];
	[params setObject:postTags forKey:@"post[tags]"];
	[params setObject:@"1" forKey:@"post[icon]"];
	//[params setObject:@"true" forKey:@"receive_sms"];
	//[params setObject:@"false" forKey:@"close_comment"];

	NSString* locationTitle = @"location title";
	CGFloat locationLatitude = 37.255109;
	CGFloat locationLongitude = 127.070973;

	[params setObject:locationTitle forKey:@"location"];
	[params setObject:[NSString stringWithFormat:@"%f", locationLatitude] forKey:@"latitude"];
	[params setObject:[NSString stringWithFormat:@"%f", locationLongitude] forKey:@"longitude"];

	// resource 에 있는 image를 파일로 읽을 수 없다.
	// "resource path에 있는 이미지 사용하기" 참고 --> http://blog.naver.com/saturna/60125097164
//	NSString* photoFilePath = [[NSBundle mainBundle] pathForResource:@"test_photo.jpg" ofType:nil];
//	photoFilePath = [[NSURL fileURLWithPath:photoFilePath] absoluteString];
//	NSData* aPhotoData = [[NSData alloc] initWithContentsOfFile:photoFilePath];

	//if (DEBUG) Me2Log(@"====> aaa");
	//NSData* aPhotoData = [UIImageJPEGRepresentation([UIImage imageNamed:@"test_photo.jpg"], 1.0) retain];
	NSData* aPhotoData = [UIImagePNGRepresentation([UIImage imageNamed:@"test_photo.png"]) retain];
	Me2DayAttach* aMe2DayAttach = [[Me2DayAttach alloc] initWithAttachData:aPhotoData
															   andFileName:@"test_photo.png"];
	[aPhotoData release];
	//if (DEBUG) Me2Log(@"====> bbb");

	[params setObject:aMe2DayAttach forKey:@"attachment"];
	[aMe2DayAttach release];

	m_me2dayRequest = [[Me2DayRequest alloc] initWithMe2DayOAuthResult:self.appDelegate.me2dayOAuthResult];
	m_me2dayRequest.delegate = self;
	m_me2dayRequest.me2dayTag = kMe2DayTagPostPhoto;

	[m_me2dayRequest requestWithMethodName:Me2DayRequestMethodCreatePost
								 andParams:[params autorelease]
							 andHttpMethod:@"POST"
							  andMultipart:YES];
}


- (void)openPhotoURLWithConfirmMessage:(NSString*)confirmMessage
{
	Me2DayUIAlertView* alertView = [[[Me2DayUIAlertView alloc]
									 initConfirmWithTitle:nil
									 message:confirmMessage
									 target:self
									 action:@selector(openPhotoURLAfterConfirmView:buttonAtIndex:)] autorelease];

	[alertView show];
}
- (void)openPhotoURLAfterConfirmView:(Me2DayUIAlertView*)alertView
					   buttonAtIndex:(NSUInteger)buttonIndex
{
	if (buttonIndex == 0)
	{
		return;
	}

	NSString* urlString = [NSString stringWithFormat:@"http://me2day.net/%@/archive/me2photo",
						   self.appDelegate.me2dayOAuthResult.userId ];
	NSURL* aURL = [[NSURL alloc] initWithString:urlString];
	[[UIApplication sharedApplication] openURL:[aURL autorelease]];
}




@end
